import React, { useState, memo, useEffect, useRef } from 'react';
import Breadcrumb from 'components/common/Breadcrumb';
import './index.less';
import { Button, Modal, Form, Input, Space, Select, Col, Row, Table } from 'antd';
import Area from 'components/Area';
import {
    PlusOutlined,
    MinusCircleOutlined,
    SmileOutlined,
    FormOutlined,
    SearchOutlined,
    RedoOutlined,
} from '@ant-design/icons';
import EditableComponent from 'components/Editable';
import {
    getLiftingControlByArea,
    getAllLiftingControl,
    LiftingControlType,
    IAreaLiftingControl,
    ILiftingControl,
} from 'api/LiftingControl';
import { useRequest } from 'ahooks';
import { IArea } from 'api/Area';
import { getAllOnlineLiftingControls } from 'api/OnlineLiftingControl';

const TypeSetlect = (control: ILiftingControl) => (
    <Select defaultValue={control.type} style={{ width: 150 }} onChange={(value) => (control.type = value)}>
        <Select.Option value={0}>{LiftingControlType[0]}</Select.Option>
        <Select.Option value={1}>{LiftingControlType[1]}</Select.Option>
        <Select.Option value={2}>{LiftingControlType[2]}</Select.Option>
    </Select>
);
/** 初始化控制箱 */
const initialLiftingControls: ILiftingControl[] = [
    {
        ipAddress: '',
        areaId: -1,
        type: 0,
        onlineNum: 0,
    },
];
const AddPile = () => {
    const [selectedArea, setSelectedArea] = useState(-1); // 选中的区域
    const areaRef: any = useRef();
    const [areaLiftingsControls, setAreaLiftingsControls] = useState<IAreaLiftingControl>(); // 区域内控制箱集合
    const [addModelVisible, setAddModelVisible] = useState(false); // 添加、控制箱弹窗
    const [liftingControls, setLiftingControls] = useState(initialLiftingControls); // 控制箱
    const [isAllAvailable, setIsAllAvailable] = useState(false); // 控制箱是否都可用
    const [onlineTableVisible, setOnlineTableVisible] = useState(false);
    /** 获取区域内的控制箱 */
    useEffect(() => {
        if (selectedArea === -1) return;
        getLiftingControlByArea({ areaId: selectedArea }).then((res) => {
            console.log(res);
            setAreaLiftingsControls(res);
        });
    }, [selectedArea]);
    /** 获取全部区域控制箱 */
    const { data: allLifitngControl } = useRequest(getAllLiftingControl);
    console.log('allLifitngControl', allLifitngControl);
    /** 获取全部在线设备 */
    const { data: allOnlineLiftingContol, run: refreshOnlineLiftingControl, loading: onlineLoading } = useRequest(
        getAllOnlineLiftingControls,
    );
    /** 表格列 */
    const columns = [
        {
            title: '设备类型',
            dataIndex: 'type',
            key: 'ipAddress',
            render: (type: number) => LiftingControlType[type],
        },
        {
            title: '控制箱IP',
            key: 'ipAddress',
            dataIndex: 'ipAddress',
        },
        {
            title: `在线设备数${areaLiftingsControls?.onlineCount}`,
            key: 'onlineNum',
            dataIndex: 'onlineNum',
        },
    ];
    /** 在线设备表格列 */
    const onlineColumns = [
        {
            title: 'IP',
            dataIndex: 'ipAddress',
        },
        {
            title: '设备类型',
            dataIndex: 'type',
            render: (type: number) => LiftingControlType[type],
        },
        {
            title: '操作',
            render: ({}, {}) => <Button>添加至管理设备</Button>,
        },
    ];
    const addPileBtnClick = () => {
        setAddModelVisible(true);
    };
    const okClick = () => {
        setIsAllAvailable(true);
    };
    const saveEdit = (control: ILiftingControl) => {
        console.log(control);
        const newLiftingControls = liftingControls.map((item) => {
            if (item.ipAddress === control.ipAddress) {
                item.type = control.type;
            }
            return item;
        });
        setLiftingControls(newLiftingControls);
    };
    return (
        <div className="add-pile">
            <Breadcrumb crumbs={['路桩配置', '添加路桩']}></Breadcrumb>
            <Button type="primary" className="mb10" onClick={addPileBtnClick}>
                设备添加
            </Button>
            <Row>
                <Col flex="300px">
                    <Area selectedArea={selectedArea} setSelectedArea={setSelectedArea} ref={areaRef}></Area>
                </Col>
                <Col flex="auto" className="pl20 pr20">
                    <div className="flex-between mb10">
                        <div className="pl20">设备管理</div>
                        <div className="pr20">
                            <Button size="small" type="text">
                                <FormOutlined />
                                编辑
                            </Button>
                        </div>
                    </div>
                    <Table dataSource={areaLiftingsControls?.list} columns={columns} pagination={false} />
                </Col>
            </Row>
            <div className="online-search-tag" onClick={() => setOnlineTableVisible(!onlineTableVisible)}>
                在线设备搜索
                <SearchOutlined />
            </div>
            {onlineTableVisible && (
                <div className="online-controls">
                    <div className="text-right mb10">
                        <RedoOutlined className="pointer mr5" onClick={refreshOnlineLiftingControl} />
                        刷新
                    </div>
                    <Table
                        loading={onlineLoading}
                        dataSource={allOnlineLiftingContol}
                        columns={onlineColumns}
                        pagination={false}
                        bordered
                    />
                </div>
            )}

            <Modal
                visible={addModelVisible}
                title="设备添加"
                okText={isAllAvailable ? '确定' : '搜索'}
                cancelText="取消"
                onOk={okClick}
                onCancel={() => setAddModelVisible(false)}
            >
                {liftingControls.map((control: ILiftingControl, index: number) => (
                    <div key={index}>
                        <Row className="mb10" align="middle">
                            <Col flex="100px" className="text-right pr10">
                                控制箱IP：
                            </Col>
                            <Col flex="auto">
                                <Input
                                    placeholder="请输入控制箱IP"
                                    defaultValue={control.ipAddress}
                                    style={{ width: 200 }}
                                />
                            </Col>
                        </Row>
                        <Row className="mb10" align="middle">
                            <Col flex="100px" className="text-right pr10">
                                设备区域：
                            </Col>
                            <Col flex="auto">
                                <Select style={{ width: 150 }}>
                                    {areaRef.current?.areas.map((area: IArea) => (
                                        <Select.Option key={area.id} value={area.id || -1}>
                                            {area.name}
                                        </Select.Option>
                                    ))}
                                </Select>
                            </Col>
                        </Row>
                        <Row className="mb10" align="middle" style={{ height: 32 }}>
                            <Col flex="100px" className="text-right pr10">
                                路桩型号：
                            </Col>
                            <Col flex="auto">
                                <EditableComponent
                                    inEditChildren={TypeSetlect(control)}
                                    unInEditChildren={LiftingControlType[control.type]}
                                    saveEdit={() => saveEdit(control)}
                                />
                            </Col>
                        </Row>
                        <Row className="mb10" align="middle" style={{ height: 32 }}>
                            <Col flex="100px" className="text-right pr10">
                                在线路桩数：
                            </Col>
                            <Col flex="auto">{control.onlineNum}</Col>
                        </Row>
                    </div>
                ))}
            </Modal>
        </div>
    );
};
export default AddPile;
